package bll

import (
	"fmt"

	. "7qule.com/sd3/CrossServer/src/bll/player/model"
	"7qule.com/sd3/CrossServer/src/common/onlinelog"
	"7qule.com/sd3/CrossServer/src/common/systemConstant"
	"7qule.com/sd3/CrossServer/src/utils"
	"public.com/goutil/syncUtil"
)

// --------------------------------初始化--------------------------------------------------

//玩家属性变动类
var (
	//玩家公会变动回调方法
	guildChangeFuncs = make(map[string]func(player *GlobalPlayer, oldGuild, newGuild string))

	//读写锁
	dataLock = syncUtil.NewRWLocker()
)

// 注册玩家公会改变事件
func RegisterGuildChangeFuncs(moduleName string, funcDefinition func(player *GlobalPlayer, oldGuild, newGuild string)) {
	if isOk, prevStack, currStack := dataLock.Lock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer dataLock.Unlock()

	if _, exists := guildChangeFuncs[moduleName]; exists {
		errMsg := fmt.Sprintf("已经注册该回调方法,moduleName:%s", moduleName)
		panic(errMsg)
	}

	if funcDefinition == nil {
		errMsg := fmt.Sprintf("注册方法不能为nil,moduleName:%s", moduleName)
		panic(errMsg)
	}

	guildChangeFuncs[moduleName] = funcDefinition
}

// 触发玩家公会改变事件
func TriggerGuildChangeEvent(player *GlobalPlayer, oldGuild, newGuild string) {
	go func() {
		defer utils.LogErrorRecover()

		if isOk, prevStack, currStack := dataLock.RLock(systemConstant.DefaultLockTime); isOk == false {
			errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
			onlinelog.ErrorLog(errMsg)
			panic(errMsg)
		}
		defer dataLock.RUnlock()

		for _, fun := range guildChangeFuncs {
			fun(player, oldGuild, newGuild)
		}
	}()
}
